/*
 * Copyright (C) 2022 KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

#include "accountlogout.h"

AccountLogout::AccountLogout(QObject *parent) : QObject(parent)
{
    getUserInfo();
}

QString AccountLogout::getUserName()
{
    return myUserName;
}

QString AccountLogout::getRealName()
{
    return myRealName;
}

qlonglong AccountLogout::logout()
{
    if (!QDBusConnection::sessionBus().isConnected()) {
        qDebug()<<(stderr, "Cannot connect to the D-Bus session bus.\n"
                "To start it, run:\n"
                "\teval `dbus-launch --auto-syntax`\n");
        return 1;
    }

    QDBusInterface interface("org.gnome.SessionManager", "/org/gnome/SessionManager", "org.gnome.SessionManager", QDBusConnection::sessionBus());

    if (interface.isValid())
    {
        interface.call("logout"); //systemDbus,method.
    }

}
void AccountLogout::getUserInfo()
{
    qlonglong uid = getuid();

    QDBusInterface user("org.freedesktop.Accounts",
                        "/org/freedesktop/Accounts",
                        "org.freedesktop.Accounts",
                        QDBusConnection::systemBus());

    QDBusMessage result = user.call("FindUserById", uid);
    QString userpath = result.arguments().value(0).value<QDBusObjectPath>().path();
    QDBusInterface *userInterface = new QDBusInterface ("org.freedesktop.Accounts",
                                          userpath,
                                        "org.freedesktop.Accounts.User",
                                        QDBusConnection::systemBus());

    QString realName = userInterface->property("RealName").value<QString>();
    QString userName = userInterface->property("UserName").value<QString>();

    if(realName == " " ){
        myRealName = userName;
        myUserName = userName;
        emit userInfoSignal(userName, userName);
    }
    else {
        myRealName = realName;
        myUserName = userName;
        emit userInfoSignal(realName, userName);
    }

    //获取用户头像
//    QString userIconPath = userInterface->property("IconFile").value<QString>();
}
